package com.baselibrary.activity;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.databinding.DataBindingUtil;
import androidx.databinding.ViewDataBinding;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.ViewModelProvider;

import com.baselibrary.action.BundleAction;
import com.baselibrary.action.TitleBarAction;
import com.baselibrary.manager.LoadingManager;
import com.baselibrary.titlebar.TitleBar;
import com.baselibrary.utils.CommonUtil;
import com.baselibrary.utils.StatusBarUtil;
import com.gyf.immersionbar.ImmersionBar;

/**
 * @author yuyang
 */
public abstract class BaseFragment extends Fragment implements TitleBarAction, BundleAction {
    private ImmersionBar mImmersionBar;

    private TitleBar mTitleBar;

    private ViewDataBinding mViewDataBinding;

    private Activity mActivity;

    public Activity getAttachActivity() {
        return mActivity;
    }

    @Override
    public void onAttach(@NonNull Context context) {
        super.onAttach(context);
        mActivity = (Activity) context;

    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        mViewDataBinding = DataBindingUtil.inflate(inflater, getLayoutId(), null, false);
        return mViewDataBinding.getRoot();
    }
    /**
     * 获取 DataBinding 要加载的布局
     *
     * @return
     */
    protected abstract int getLayoutId();
    /**
     * 加载完成布局后，需要处理的动作
     */
    protected abstract void init();

    /**
     * 子类获取其 DataBinding 对象的方法
     *
     * @param <T>
     * @return
     */
    protected <T> T getDataBinding() {
        return (T) mViewDataBinding;
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        // 获取 TitleBar 对象，并设立点击事件
        if (getTitleBar() != null) {
            getTitleBar().setOnTitleBarListener(this);
        }
        // 初始化沉浸式状态栏
        initImmersion();
        init();
    }

    /**
     * 返回键点击事件，默认不处理，交给 Activity 处理
     *
     * @param keyCode
     * @param event
     * @return
     */
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        // 默认不拦截按键事件， 回传给 Activity
        return false;
    }

    @Override
    public Bundle getBundle() {
        return getArguments();
    }

    /**
     * 初始化沉浸式
     */
    protected void initImmersion() {
        // 初始化沉浸式状态栏
        if (isStatusBarEnabled()) {
            createStatusBarConfig().init();
            // 设置标题栏沉浸
            if (getTitleBar() != null) {
                ImmersionBar.setTitleBar(getAttachActivity(), getTitleBar());
            }
        }
    }

    protected ImmersionBar createStatusBarConfig() {
        mImmersionBar = ImmersionBar.with(getAttachActivity())
                .statusBarDarkFont(statusBarDarkFont());
        return mImmersionBar;
    }
    public void setStatusBarDarkTheme(boolean dark) {
        if (!StatusBarUtil.setStatusBarDarkTheme(getActivity(), dark)) {
            StatusBarUtil.setStatusBarColor(getActivity(), dark ? com.baselibrary.R.color.black : com.baselibrary.R.color.white);
        }
    }

    // 5.0版本以上
    @SuppressLint("NewApi")
    public void setStatusBarHeight(View view) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            View decorView = getActivity().getWindow().getDecorView();
            int option = View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_STABLE;
            decorView.setSystemUiVisibility(option);
            getActivity().getWindow().setStatusBarColor(Color.TRANSPARENT);
            if (view.findViewById(com.baselibrary.R.id.status_bar) != null) {
                view.findViewById(com.baselibrary.R.id.status_bar).setVisibility(View.VISIBLE);
                int statusBarHeight = CommonUtil.getStatusBarHeight(getActivity());
                view.findViewById(com.baselibrary.R.id.status_bar).getLayoutParams().height = statusBarHeight;
            }
        }
    }
    // 给所有的fragment提供的函数，可以顺利的拿到 ViewModel
    public ViewModelProvider getFragmentViewModelProvider(Fragment fragment) {
        return new ViewModelProvider(fragment, fragment.getDefaultViewModelProviderFactory());
    }
    protected void showLoadingDialog() {
        showLoadingDialog(null);
    }

    protected void showLoadingDialog(String msg) {
        LoadingManager.showLoadingDialog(getActivity(), msg);
    }

    protected void hideLoadingDialog() {
        LoadingManager.hideLoadingDialog(getActivity());
    }
    public void openActivity(Class<?> mClass, Bundle mBundle) {
        Intent intent = new Intent(getActivity(), mClass);
        if (mBundle != null) {
            intent.putExtras(mBundle);
        }
        startActivity(intent);
    }

    /**
     * 获取状态栏字体颜色
     */
    protected boolean statusBarDarkFont() {
        // 返回真表示黑色字体
        return true;
    }

    /**
     * 是否在Fragment使用沉浸式
     */
    protected boolean isStatusBarEnabled() {
        return true;
    }



    protected void onFragmentResult(Bundle bundle) {

    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
    }


    @Override
    public void onDetach() {
        mActivity = null;
        super.onDetach();
    }

    @Nullable
    @Override
    public TitleBar getTitleBar() {
        if (mTitleBar == null && mViewDataBinding != null) {
            mTitleBar = findTitleBar((ViewGroup) mViewDataBinding.getRoot());
        }
        return mTitleBar;
    }
}
